package com.markerhub.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.alibaba.excel.EasyExcel;
import com.google.code.kaptcha.Producer;
import com.markerhub.common.lang.Const;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.SysUser;
import com.markerhub.entity.TFacilityBase;
import com.markerhub.entity.TProjectBase;
import com.markerhub.povo.TPayOrderVo;
import com.markerhub.povo.TPayOrderVos;
import com.markerhub.service.SysUserService;
import com.markerhub.service.TFacilityBaseService;
import com.markerhub.service.TFacilityFunctionService;
import com.markerhub.service.TPayOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.Principal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController
public class AuthController extends BaseController{

	@Autowired
	Producer producer;

	@Autowired
	TFacilityBaseService tFacilityBaseService;
	@Autowired
	TFacilityFunctionService tFacilityFunctionService;
	@Autowired
	TPayOrderService tPayOrderService;


	@GetMapping("/captcha")
	public Result captcha() throws IOException {

		String key = UUID.randomUUID().toString();
		String code = producer.createText();

		// 为了测试
		key = "aaaaa";
		code = "11111";

		BufferedImage image = producer.createImage(code);
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", outputStream);

		BASE64Encoder encoder = new BASE64Encoder();
		String str = "data:image/jpeg;base64,";

		String base64Img = str + encoder.encode(outputStream.toByteArray());

		redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);

		return Result.succ(
				MapUtil.builder()
						.put("token", key)
						.put("captchaImg", base64Img)
						.build()

		);
	}

	/**
	 * 获取用户信息接口   用户信息后续可以放在redis中进行保存，不必每次访问一个模块就查询一次
	 * @param principal
	 * @return
	 */
	@GetMapping("/sys/userInfo")
	public Result userInfo(Principal principal) {

		SysUser sysUser = sysUserService.getByUsername(principal.getName());
		TProjectBase byId = tProjectBaseService.getById(sysUser.getProjectid());
		Boolean Projecttrue;
		if (byId.getProjectid().equals("f33dd53f33ffaebee7dd9d46239fa0db")){
			Projecttrue=true;
		}else {
			Projecttrue=false;
		}
		return Result.succ(MapUtil.builder()
				.put("id", sysUser.getId())
				.put("username", sysUser.getUsername())
				.put("avatar", sysUser.getAvatar())
				.put("created", sysUser.getCreated())
				.put("Projecttrue", Projecttrue)
				.put("projectname", byId.getProjectName())
				.put("projectid", byId.getProjectid())
				.map()
		);
	}

	/* 测试在线导出一个execl */
//	@RequestMapping("/download")
//	//@PreAuthorize("hasAuthority('sys:facility:export')")
//	public void downloadexecl(HttpServletResponse response) throws Exception {
////		String number = requireVo.getNumber();
////		String projectid = requireVo.getProjectid();
////		String orderNumber = requireVo.getOrderNumber();
////		LocalDate dateup = requireVo.getDate1();
////		LocalDate datedown = requireVo.getDate2();
////		String defarystatus = requireVo.getDefarystatus();
//		// 这里的业务数据根据自己的业务场景去做查询
//		List<TPayOrderVo> list = tPayOrderService.getOrderList(0,0,null,null,null,null,null,null);
//		List<TPayOrderVos>  tPayOrderVos = new ArrayList<>();
//		for (TPayOrderVo TPayOrderVo:list ) {
//			TPayOrderVos tPayOrderVos1 = new TPayOrderVos();
//			BeanUtils.copyProperties(TPayOrderVo,tPayOrderVos1);
//			tPayOrderVos.add(tPayOrderVos1);
//		}
//
//
//		System.out.println(tPayOrderVos);
//		System.out.println("需要导出的数据");
//
//		response.setContentType("application/vnd.ms-excel");
//		response.setCharacterEncoding("utf-8");
//		String fileName = URLEncoder.encode("测试", "UTF-8");
//		response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
//		EasyExcel.write(response.getOutputStream()).sheet("第一个sheet").doWrite(tPayOrderVos);
////		response.setContentType("application/vnd.ms-excel");
////		response.setCharacterEncoding("utf-8");
////		String fileName = URLEncoder.encode("测试", "UTF-8");
////		response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
////		EasyExcel.write(response.getOutputStream()).sheet("第一个sheet").doWrite(data());
//		//return Result.succ(null);
//	}

	protected List<?> data(){
		List<List<String>> rowList = new ArrayList<>();
		List<String> cell = new ArrayList<>();
		cell.add("good1");
		cell.add("good2");
		cell.add("good3");
		rowList.add(cell);
		return rowList;
	}




	@GetMapping("/infoBase/{id}")
	@PreAuthorize("hasAuthority('sys:facility:infoBase')")
	@ResponseBody
	public Result infoBase(@PathVariable("id") String id ){
		TFacilityBase byId = tFacilityBaseService.getById(id);
		System.out.println("依据ID 查询对应的设备信息 === "+byId);
		return Result.succ(byId);
	}


}
